package com.cat.dataStructure02;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-frequency-of-an-element-after-performing-operations-ii/?envType=daily-question&envId=2025-10-22
 * @create 2025/10/22 15:04
 * @since JDK17
 */

public class Solution41 {
    public int maxFrequency(int[] nums, int k, int numOperations) {
        Arrays.sort(nums);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int x : nums) {
            map.merge(x, 1, Integer::sum);
        }
        int ans = 0, l, m, r, n = nums.length;
        for (l = r = m = 0; l < n; l++) {
            while (m < n && nums[l] + k >= nums[m]) {
                m++;
            }
            int t = nums[m - 1] + k;
            while (r < n && t >= nums[r]) {
                r++;
            }
            int score = r - l;
            if (score < numOperations) {
                ans = Math.max(ans, score);
            } else {
                ans = Math.max(ans, map.get(nums[m]) + numOperations);
            }
        }

        return ans;
    }
}
